/*
 * @Author: yuanming
 * @Date: 2023-10-27 13:30:52
 * @LastEditors: yuanming
 * @LastEditTime: 2024-09-11 13:47:16
 * @Description: fileDescription
 */
import axios from 'axios'
import { ElMessageBox, ElMessage } from 'element-plus'
import router from '@/router/index.js'
import { baseURL } from './url'

let showMessage = false

// create an axios instance
const service = axios.create({
    baseURL, // url = base url + request url
    timeout: 50000, // request timeout
})

// request interceptor
service.interceptors.request.use(
    (config) => {
        const obj = {
            ...config,
            headers: {
                Session: sessionStorage.getItem('token'),
            },
        }
        return obj
    },
    (error) => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    },
)

// response interceptor
service.interceptors.response.use(
    (res) => {
        const {
            code, result, message, data, msg,
        } = res.data
        switch (code) {
            case 200:
                return result || data
            case 401:
                if (showMessage) return
                ElMessageBox.alert('身份信息已过期，请重新登陆', '提示', {
                    confirmButtonText: '重新登陆',
                    showClose: false,
                    type: 'error',
                    callback: () => {
                        router.push('/login')
                    },
                })
                showMessage = true
                setTimeout(() => {
                    showMessage = false
                }, 3000)
                break
            case 500:
                ElMessage.closeAll()
                ElMessage.error(message || msg)
                break
            default: break
        }
    },
    (error) => {
        if (error && error.response) {
            switch (error.response.status) {
                // 401 token失效
                case 401:
                    ElMessageBox.alert('身份信息已过期，请重新登陆', '提示', {
                        confirmButtonText: '重新登陆',
                        showClose: false,
                        type: 'error',
                    })
                    break

                // 403 服务器拒绝访问
                case 403:
                    // router.push('/error/403')
                    break

                // 404 访问的资源不存在
                case 404:
                    // router.push('/error/404')
                    break

                // 500 服务器错误
                case 500:
                    // router.push('/error/500')
                    break
                default: break
            }

            return Promise.reject(error)
        }
    },
)

export default service
